package com.golte.common;

import com.github.pagehelper.PageInfo;
import com.golte.exception.BusinessException;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.ArrayList;
import java.util.List;


@Builder
@AllArgsConstructor
@NoArgsConstructor
@Data
public class PageResult {
    /**
     * 当前页码
     */
    private int pageNum;
    /**
     * 每页数量
     */
    private int pageSize;
    /**
     * 记录总数
     */
    private long totalSize;
    /**
     * 页码总数
     */
    private int totalPages;
    /**
     * 数据模型
     */
    private List<?> pageList;

    public PageResult(PageInfo<?> pageInfo) {
        this.pageNum = pageInfo.getPageNum();
        this.pageSize = pageInfo.getPageSize();
        this.totalSize = pageInfo.getTotal();
        this.totalPages = pageInfo.getPages();
    }

    /**
     * 分页
     * @param data     分页原始数据
     * @param pageNum  当前页
     * @param pageSize 当前页数量
     * @return
     */
    public PageResult autoPage(List<?> data, int pageNum, int pageSize) {
        this.pageNum = pageNum;
        this.pageSize = pageSize;
        if (data == null || data.size() == 0) {
            this.totalSize = 0;
            this.totalPages = 0;
            this.pageList = new ArrayList<>();
            return this;
        }
        if (pageNum == 0 || pageSize == 0) {
            throw new BusinessException("pageNum或者pageSize不能等于0");
        }
        if (pageNum < 0 || pageSize < 0) {
            throw new BusinessException("pageNum或者pageSize不能小于0");
        }
        this.totalSize = data.size(); // 数据总大小
        this.totalPages = 1;
        // 1 判断分页数据是否大于pageSize
        if (this.totalSize <= pageSize) {
            this.pageList = data;
            return this;
        } else {
            this.totalPages = (int)(Math.ceil(Double.valueOf(this.totalSize) / Double.valueOf(pageSize)));
        }
        // 2 获取最后一页
        if (pageNum * pageSize > data.size()) {
            this.pageList = data.subList((this.totalPages - 1) * pageSize, data.size());
            return this;
        }
        // 3 非最后页
        this.pageList = data.subList((pageNum - 1) * pageSize, pageNum * pageSize);
        return this;
    }
}
